package com.chiaching.framwork.core.handler.security;

import com.chiaching.framwork.domian.bean.SuperMallUserDetail;
import com.chiaching.framwork.domian.constant.CoreConstant;
import com.chiaching.framwork.utils.CookieUtil;
import com.chiaching.framwork.utils.RedisUtils;
import com.chiaching.framwork.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author jiajing.he
 * @date 2021/7/27 下午1:50
 */
@Component
@Slf4j
public class SuperMallUserTokenAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private SuperMallSecurityUserApi superMallSecurityUserApi;
    @Resource
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = CookieUtil.getValueInCookies(httpServletRequest, CoreConstant.USER_TOKEN);
        SuperMallUserDetail superMallUserDetail = redisUtils.getObject(token, SuperMallUserDetail.class);
        boolean isLogin = Objects.nonNull(superMallUserDetail);
        if (!isLogin) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        SuperMallUserDetail superMallUserDetailForRemote = superMallSecurityUserApi.queryById(superMallUserDetail.getId());
        log.info("security获取用户信息 param[userId{}], res[{}]",superMallUserDetail.getId(),superMallUserDetailForRemote);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(superMallUserDetailForRemote, superMallUserDetailForRemote.getPassword(), superMallUserDetailForRemote.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
